package com.kbbywyclient.ui.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.data.entity.HotRec;
import com.kbbywyclient.data.entity.TaskTab;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.TaskModule;
import com.kbbywyclient.presenter.TaskPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.HotRecAdapter;
import com.kbbywyclient.ui.contarct.TaskContract;
import com.kbbywyclient.ui.helper.ShareHelper;
import com.kbbywyclient.ui.pop.SharePopWin;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.ImageLoaderUtils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.ptr.PullRefreshLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by Jiangzx on 2017/8/25 16:19.
 */

public class TaskActivity extends BaseActivity implements TaskContract.View{
    @BindView(R.id.v_toolbar)
    CustomToolBar toolBar;

    @BindView(R.id.ptr_layout)
    PtrClassicFrameLayout ptrLayout;

    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;

    @BindView(R.id.view_divider_top)
    View dividerTop;

    @BindView(R.id.iv_one_key_share)
    ImageView ivOneKeyShare;
    @BindView(R.id.tv_one_key_share)
    TextView tvOneKeyShare;

    @BindView(R.id.iv_face_to_face)
    ImageView ivFaceToFace;
    @BindView(R.id.tv_face_to_face)
    TextView tvFaceToFace;

    @BindView(R.id.sr_layout)
    SmartRefreshLayout srLayout;

    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;

    private HotRecAdapter adapter;

    @Inject
    TaskPresenter presenter;

    ShareHelper shareHelper;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_task;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        final PullRefreshLayout header=new PullRefreshLayout(this);
        header.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                StringUtil.dip2px(this,45)));
        ptrLayout.setHeaderView(header);
        ptrLayout.addPtrUIHandler(header);
        ptrLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                refresh();
            }
        });

        appBarLayout.addOnOffsetChangedListener((appBarLayout1, verticalOffset) -> {
            if(verticalOffset==0){
                ptrLayout.setEnabled(true);
            }else{
                ptrLayout.setEnabled(false);
            }
            float progress =
                    (float) (((int) (Math.abs(verticalOffset) / (appBarLayout1.getTotalScrollRange() * 0.01))) * 0.01);
            dividerTop.setAlpha(progress);
        });
        srLayout.setOnLoadmoreListener(refreshLayout -> {
            presenter.pageNo++;
            loadListData();
        });

        toolBar.setLeftViewOnClickLinster(view->finish());
    }

    private void startRefresh() {
        new Handler().postDelayed(() -> ptrLayout.autoRefresh(),200L);
    }

    private void refresh(){
        tvOneKeyShare.setTag(null);
        tvFaceToFace.setTag(null);
        presenter.loadTaskTab();

        presenter.clearList();
        if(adapter!=null){
            adapter.notifyDataSetChanged();
        }
        loadListData();
    }

    @Override
    public void initData() {
        final LinearLayoutManager layoutManager=new LinearLayoutManager(TaskActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&
                        layoutManager.findFirstCompletelyVisibleItemPosition()==0){
                    appBarLayout.setExpanded(true,true);
                }
            }
        });

        startRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("信用卡任务");
    }

    private void loadListData(){
        if(PreUtils.isLogin(this)){
            presenter.loadTaskHotRec(presenter.pageNo,
                    String.valueOf(PreUtils.getUser(this).getSalesID()));
        }else{
            presenter.loadTaskHotRec(presenter.pageNo,null);
        }
    }

    @OnClick({R.id.ll_one_key_share,R.id.ll_face_to_face})
    void onClick(View view){
        Context context=this;
        switch (view.getId()){
            case R.id.ll_one_key_share:
                    //一键分享
                    Object object=tvOneKeyShare.getTag();
                    if(object==null){
                        ToastUtil.showLong("请刷新后重新操作");
                    }else{
                        TaskTab.Bean bean= (TaskTab.Bean) object;
                        final ShareHelper.ShareBody shareBody =new ShareHelper.ShareBody();
                        shareBody.url= API.WEB_ADDRESS+
                                bean.getShareURL();
                        if(PreUtils.isAuthenticated(context)){
                            shareBody.title="您的好友"+
                                    PreUtils.getTrueName(context)+
                                    "邀请您申请信用卡,优惠好礼享不停";
                        }else{
                            shareBody.title="您的好友邀请您申请信用卡,优惠好礼享不停";
                        }
                        shareBody.statisticsTitle="一键分享";
                        share(shareBody,"信用卡任务-一键分享");
                    }

                break;
            case R.id.ll_face_to_face:
                //面对面
                setScreenAction("分享","信用卡任务-面对面分享");
                    Object faceToFaceObject=tvOneKeyShare.getTag();
                    if(faceToFaceObject==null){
                        ToastUtil.showLong("请刷新后重新操作");
                    }else{
                        TaskTab.Bean bean= (TaskTab.Bean) faceToFaceObject;
                        final String shareUrl=API.WEB_ADDRESS+
                                bean.getShareURL();
                        HashMap<String,Object> params=new HashMap<>();
                        params.put(ShareFaceToFaceActivity.SHARE_URL_S,shareUrl);
                        ActivitySkipUtil.skipAnotherActivity(TaskActivity.this,
                                ShareFaceToFaceActivity.class,params);
                    }

                break;
        }
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getTaskComponent(new TaskModule(this)).inject(this);
    }

    @Override
    public void finishRefresh() {
        if(ptrLayout.isRefreshing()){
            new Handler().postDelayed(() -> ptrLayout.refreshComplete(),200L);
        }
    }

    @Override
    public void onTaskTabSuccess(List<TaskTab.Bean> data) {
        if(data.size()>=2){
            TaskTab.Bean oneKeyShare=data.get(0);
            ImageLoaderUtils.displayImageDefaultRes(ivOneKeyShare,
                    API.PIC_ADDRESS+oneKeyShare.getPicture_path(),
                    R.mipmap.icon_share);
            ViewUtils.setText(tvOneKeyShare,oneKeyShare.getName());
            tvOneKeyShare.setTag(oneKeyShare);
            TaskTab.Bean faceToFace=data.get(1);
            ImageLoaderUtils.displayImageDefaultRes(ivFaceToFace,
                    API.PIC_ADDRESS+faceToFace.getPicture_path(),
                    R.mipmap.icon_qr_code_circle);
            ViewUtils.setText(tvFaceToFace,faceToFace.getName());
            tvFaceToFace.setTag(faceToFace);
        }
    }

    @Override
    public void setListUi(List<HotRec> data, boolean canLoadMore) {
        if(adapter==null){
            adapter=new HotRecAdapter(data);
            adapter.setOnItemClickedListener((hotRec,action)->{
                    switch (action){
                        case HotRecAdapter.OnItemClickedListener.ACTION_GO_DETAILED:
                            setScreenAction("推荐","信用卡任务-热门推荐-列表项点击",hotRec.getName());
                            if(TextUtils.isEmpty(hotRec.getJub_url())){
                                //进详情页面
                                int salesId = PreUtils.getUser(TaskActivity.this).getSalesID();
                                String detailedUrl=API.CARD_DETAILE_URL+
                                        "?cardID="+hotRec.getID() +
                                        "&saleID=" + salesId+
                                        "&Code="+ Constants.DCP021702;
                                HashMap<String,Object> params=new HashMap<>();
                                params.put(WebViewActivity.KEY_URL_S,detailedUrl);
                                params.put(WebViewActivity.KEY_TITLE_S,
                                        getString(R.string.text_card_share_details));
                                params.put(WebViewActivity.KEY_SCREEN_NAME_S,
                                        "信用卡分享详情");
                                params.put(WebViewActivity.KEY_CARD_NAME,
                                        hotRec.getName());
                                ActivitySkipUtil.skipAnotherActivity(TaskActivity.this,
                                        WebViewActivity.class,params);
                            }
                            break;
                        case HotRecAdapter.OnItemClickedListener.ACTION_SHARE:
                            Context context=TaskActivity.this;
                            if(TextUtils.isEmpty(hotRec.getJub_url())){
                                //分享
                                final ShareHelper.ShareBody shareBody = new ShareHelper.ShareBody();
                                if(PreUtils.isAuthenticated(context)){
                                    shareBody.title="您的好友"+
                                            PreUtils.getTrueName(context)+
                                            "邀请您申请"+hotRec.getName()+
                                            ",优惠好礼享不停";
                                }else{
                                    shareBody.title="您的好友邀请您申请"+
                                            hotRec.getName()+
                                            ",优惠好礼享不停";
                                }
                                shareBody.statisticsTitle=hotRec.getName();
                                shareBody.url = API.WEB_ADDRESS +hotRec.getShareURL();
                                share(shareBody,"信用卡任务-热门推荐-列表项分享");
                            }else{
                                //进第三方网页
                                HashMap<String,Object> webParams=new HashMap<>();
                                webParams.put(WebViewActivity.KEY_TITLE_S,
                                        context.getString(R.string.text_bank_recommend_page));
                                webParams.put(WebViewActivity.KEY_URL_S,hotRec.getJub_url());
                                ActivitySkipUtil.skipAnotherActivity(TaskActivity.this,
                                        WebViewActivity.class,webParams);
                            }
                            break;
                    }
            });
        }
        if(recyclerView.getAdapter()==null){
            recyclerView.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        srLayout.finishLoadmore();
        if(canLoadMore){
            srLayout.setLoadmoreFinished(false);
        }else{
            srLayout.setLoadmoreFinished(true);
        }
    }

    @Override
    public void loadListEmpty() {
        srLayout.finishLoadmore();
    }

    public void share(ShareHelper.ShareBody shareBody,String from) {
        new SharePopWin(this, platForm -> {
            shareBody.platForm = platForm;
            if (shareHelper == null) {
                shareHelper = new ShareHelper(TaskActivity.this,from);
            }
            shareHelper.setFrom(from);
            shareHelper.share(shareBody);
        }).showAtLocation(toolBar, Gravity.NO_GRAVITY, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (shareHelper != null) {
            shareHelper.onActivityResult(requestCode, resultCode, data);
        }
    }
}
